/**
@description portal_web文件

@copyright    Copyright 2021 高灯科技
@version      1.0.0
@link         https://www.goldentec.com
@author       venki.chen <venki.chen@goldentec.com>
@datetime     2021/12/9 16:28
*/

package main

import (
	"context"
	"gitee.com/venki/go_study_accumulate/go_review/20211208/proto/sum"
	"github.com/micro/go-micro/web"
	"net/http"
	"strconv"
)

var (
	srvClient sum.SumService
)

//
//	main
//	@Description
//  @maxim from focus to execute
//  @author venki.chen
//  @createdtime 2021-12-10 17:36:48
//  @updatedtime 2021-12-10 17:36:48
//
func main() {
	// 1. 创建服务
	service := web.NewService(
		web.Name("go.micro.learning.web.portal"),
		web.Address(":8088"),
		web.StaticDir("html"), // 声明一个静态目录
	)

	// 2. 服务初始化
	err := service.Init()
	if err != nil {
		panic(err)
	}

	// 3. 挂载接口（将接口暴露出去）
	srvClient = sum.NewSumService("go.micro.portal.srv.sum", service.Options().Service.Client())
	service.HandleFunc("/portal/sum", Sum)

	// 启动服务
	err = service.Run()
	if err != nil {
		panic(err)
	}
}

func Sum(w http.ResponseWriter, r *http.Request) {
	inputString := r.URL.Query().Get("input")
	input, _ := strconv.ParseInt(inputString, 10, 10)

	req := &sum.SumRequest{
		Input: input,
	}

	// 客户端
	rsp, err := srvClient.GetSum(context.Background(), req)
	if err != nil {
		panic(err)
	}

	w.Write([]byte(strconv.Itoa(int(rsp.Output))))
}
